<template>
  <div class="sticker-custom" v-if="showButton">
    <el-button type="danger" @click="showDialog">{{ $t('传快递单') }}</el-button>
    <el-dialog
      :title="$t('传快递单')"
      :visible.sync="dialog"
      class="sticker-dialog"
    >
      <template v-if="order.isSpecial">
        <div class="mgb20 font-red">当前订单没有平台运输单，系统无法获取收件人信息，请联系客户处理</div>
      </template>

      <template v-else>
        <div class="font-grey">{{$t('请根据下列买家信息使用快递发货并上传相应的快递单号')}}</div>
        <div class="mgb20 font-red">{{$t('点击买家信息即可一键复制')}}</div>
      </template>

      <el-form
        ref="form"
        :model="currentForm"
        label-width="140px"
        :rules="rules"
      >
        <el-form-item :label="$t('order.物流商')">
          <el-select v-model="currentForm.logisticsType" placeholder="请选择">
            <el-option label="FedEx" value="FedEx"></el-option>
            <el-option label="estafeta" value="estafeta"></el-option>
            <el-option label="DHL" value="DHL"></el-option>
            <el-option label="iMile" value="iMile"></el-option>
            <el-option label="Big" value="Big"></el-option>
            <el-option label="REDPACK" value="REDPACK"></el-option>
            <el-option label="ampm" value="ampm"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('快递单号')" prop="trackingNumber" style="width: 600px;">
          <div style="display: flex; align-items: center;">
            <el-input style="width: 400px;" v-model="currentForm.trackingNumber"></el-input>
          </div>
        </el-form-item>

        <el-form-item
          v-for="(item, index) in trackingNumberArr"
          :key="index"
          :label="$t('快递单号')"
          :prop="item.requiredPop"
          style="width: 600px;"
        >
          <div style="display: flex; align-items: center;">
            <el-input style="width: 400px;" v-model="trackingNumberList[item.requiredPop]"></el-input>
            <i class="el-icon-remove mgl10" style="cursor: pointer; color: red; font-size: 20px;" @click="removeTrackingNumber(index)"></i>
          </div>
        </el-form-item>

        <el-button
          class="mgb20"
          size="mini"
          type="primary"
          style="margin-left: 140px"
          @click="addTrackingNumber()"
        >
          +添加更多快递单号
        </el-button>

        <el-form-item :label="$t('送达时间')" prop="speed" v-if="false">
          <el-input-number
            v-model="currentForm.speed"
            :min="1"
            :step="1"
          ></el-input-number>
          <div class="font-grey f13 font-bold">{{$t('承诺产品交付所需的小时数，从传快递单之日起算')}}</div>
        </el-form-item>
        <el-form-item :label="$t('送达时间')" prop="datetime" v-if="order.accountTypeNum === 1 && !order.isSpecial">
          <el-date-picker
            v-model="currentForm.datetime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="$t('common.Please select')"
          >
          </el-date-picker>
          <div class="font-grey f13 font-bold">{{$t('通过物流面单查询到的包裹最晚安排递送日期时间')}}</div>
        </el-form-item>

        <template v-if="order.receivingInformationData !== null">
          <el-form-item label="receiver name">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_name)">{{order.receivingInformationData.buyer_name}}</el-link>
          </el-form-item>
          <el-form-item label="receiver phone">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_phone)">{{order.receivingInformationData.buyer_phone}}</el-link>
          </el-form-item>
          <el-form-item label="zip code">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_postal_code)">{{order.receivingInformationData.buyer_postal_code}}</el-link>
          </el-form-item>
          <el-form-item label="city">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_city)">{{order.receivingInformationData.buyer_city}}</el-link>
          </el-form-item>
          <el-form-item label="state">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_state)">{{order.receivingInformationData.buyer_state}}</el-link>
          </el-form-item>
          <el-form-item label="address">
            <el-link :underline="false" @click="copyText(order.receivingInformationData.buyer_address)">{{order.receivingInformationData.buyer_address}}</el-link>
          </el-form-item>
        </template>

        <template v-else-if="order.shipping">
          <el-form-item label="receiver name">
            <el-link :underline="false" @click="copyText(shipping.receiverName)">{{shipping.receiverName}}</el-link>
          </el-form-item>
          <el-form-item label="receiver phone">
            <el-link :underline="false" @click="copyText(shipping.receiverPhone)">{{shipping.receiverPhone}}</el-link>
          </el-form-item>
          <el-form-item label="zip code">
            <el-link :underline="false" @click="copyText(shipping.zipCode)">{{shipping.zipCode}}</el-link>
          </el-form-item>
          <el-form-item label="address line" v-if="order.accountTypeNum === 1">
            <el-link :underline="false" @click="copyText(shipping.addressLine)">{{shipping.addressLine}}</el-link>
          </el-form-item>
          <el-form-item label="comment"  v-if="order.accountTypeNum === 1">
            <el-link :underline="false" @click="copyText(shipping.comment)">{{shipping.comment}}</el-link>
          </el-form-item>
          <el-form-item label="neighborhood"  v-if="order.accountTypeNum === 1">
            <el-link :underline="false" @click="copyText(shipping.neighborhood)">{{shipping.neighborhood}}</el-link>
          </el-form-item>
          <el-form-item label="city">
            <el-link :underline="false" @click="copyText(shipping.city)">{{shipping.city}}</el-link>
          </el-form-item>
          <el-form-item label="state"  v-if="order.accountTypeNum === 1">
            <el-link :underline="false" @click="copyText(shipping.state)">{{shipping.state}}</el-link>
          </el-form-item>
          <el-form-item label="address">
            <el-link :underline="false" @click="copyText(shipping.address)">{{shipping.address}}</el-link>
          </el-form-item>
        </template>

        <template v-else>
          <el-empty></el-empty>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">{{$t('common.cancel')}}</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {copyToClipboard} from "@/utils";
import {stickerCustomOrder} from "@/api/order";

export default {
  name: 'StickerCustomButton',
  props:{
    order: {
      type: Object,
    }
  },
  computed: {
    shipping(){
      return this.order.shipping ? this.order.shipping : {}
    },
    showButton(){
      if (this.order.orderStatus === 1 && this.order.isSpecial === true && !this.order.shipping && this.order.receivingInformationData.id) {
        return true
      }
      if (this.order.accountTypeNum === 1) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping.logisticMode === 'custom' && this.order.shipping.status === 'pending'
        flag = flag && this.order.ignore === 0
        return flag
      }
      if (this.order.accountTypeNum === 4) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping.shippingId && this.order.performanceType === 2
        flag = flag && this.order.ignore === 0
        return flag
      }
      if (this.order.accountTypeNum === 6) {
        let flag = (this.order.orderStatus === 1 || this.order.orderStatus === 6) && this.order.shipping && this.order.shipping_type === 'SELLER'
        flag = flag && this.order.ignore === 0
        return flag
      }
      // 小包订单
      if (this.order.accountTypeNum === 7 && (this.order.orderStatus === 1 || this.order.orderStatus === 6)) {
        return true
      }
      return false
    }
  },
  data(){
    return {
      dialog: false,
      loading: false,
      currentForm: {
        accountId: '',
        trackingNumber: '',
        datetime: '',
        speed: 72,
        logisticsType: 'FedEx',
        trackingNumberList: [],
      },
      trackingNumberArr: [],
      trackingNumberList: {},
      rules: {
        trackingNumber: [
          { required: true,message: this.$t('common.pleaseFillIn'), trigger: 'blur' },
        ],
        speed: [
          { required: true,trigger: 'change',type: 'number', message: this.$t('请填写正确的送达时间'), },
          { min: 1 ,type: 'number', message: this.$t('请填写正确的送达时间'), },
        ],
        datetime: [
          {required: true, }
        ],
      },
    }
  },
  methods: {
    showDialog(){
      this.dialog = true
      this.currentForm.accountId = this.order._accountId
      this.currentForm.trackingNumber = '';
      this.currentForm.datetime = '';
      this.currentForm.speed = 72;
    },
    copyText(text){
      copyToClipboard(text)
        .then(res=>{
          this.$successMessage('copy success')
        })
    },
    submitForm(){
      this.$refs.form.validate(valid=>{
        if(!valid){
          return;
        }

        const trackingNumbers = Object.values(this.trackingNumberList);

        const postData = {
          shippingId: this.shipping.shippingId,
          accountId: this.currentForm.accountId,
          trackingNumber: this.currentForm.trackingNumber,
          speed: this.currentForm.speed,
          datetime: this.currentForm.datetime,
          logisticsType: this.currentForm.logisticsType,
          orderId: this.order.orderId,
          trackingNumberList: trackingNumbers,
          accountTypeNum: this.order.accountTypeNum,
        }
        console.log(postData)
        this.loading = true
        stickerCustomOrder(postData)
          .then(res=>{
            this.loading = false
            if(res.error !== 0){
              this.$errorMessage(res.message)
            }else{
              this.$successMessage(res.message)
              this.dialog = false
              this.$emit('changeOrder',true)
            }
          })
      })
    },

    addTrackingNumber() {
      // 添加新的数组元素
      this.trackingNumberArr.push({
        requiredPop: `trackingNumber${this.trackingNumberArr.length + 1}`,
        trackingNumber: '',
      });

      this.$set(this.trackingNumberList, `trackingNumber${this.trackingNumberArr.length}`, '');
    },

    removeTrackingNumber(index) {
      // 删除数组元素
      this.trackingNumberArr.splice(index, 1);

      // 删除跟踪号码列表中的对应项
      const removedKey = `trackingNumber${index + 1}`;
      this.$delete(this.trackingNumberList, removedKey);

      // 重新排序 requiredPop 和 rules 数据
      for (let i = index; i < this.trackingNumberArr.length; i++) {
        const newIndex = i + 1;
        const oldKey = `trackingNumber${newIndex + 1}`;
        const newKey = `trackingNumber${newIndex}`;
        this.trackingNumberArr[i].requiredPop = newKey;
        this.$set(this.trackingNumberList, newKey, this.trackingNumberList[oldKey]);
        this.$delete(this.trackingNumberList, oldKey);
      }
    },

  },

}

</script>

<style scoped lang="scss">
.sticker-custom{
  .sticker-dialog{
    text-align: left;
  }
}
</style>
